package giit.computerbase.action;

import giit.computerbase.server.ChangePasswordServer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * User: tum0r
 * Package Name: ${PACKAGE_NAME}
 * Time: 2018-11-29 Thursday 18:38:30
 */
public class ChangePasswordServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user = (String) request.getSession().getAttribute("user");
        boolean isManager = (boolean) request.getSession().getAttribute("manager");
        if (user == null || user.equals("") || !isManager) {
            response.sendRedirect("index");
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String again = request.getParameter("again");
        String toPath = "warn.jsp?";
        if (username != null && !username.equals("") &&
                password != null && !password.equals("") &&
                again != null && !again.equals("")) {
            ChangePasswordServer changePasswordServer = new ChangePasswordServer();
            if (changePasswordServer.judgeUser(username)) {
                if (password.equals(again)) {
                    changePasswordServer.change(username, password);
                    toPath += ("state=panel-primary&title=" + URLEncoder.encode("修改密码") + "&context=" + URLEncoder.encode("修改成功\n\n用户名：") + username + URLEncoder.encode("\n\n新密码：") + password + "&preview=manager.jsp");
                } else {
                    toPath += ("state=panel-danger&title=" + URLEncoder.encode("修改密码") + "&context=" + URLEncoder.encode("修改失败，两次密码输入不一致") + "&preview=manager.jsp");
                }
            } else {
                toPath += ("state=panel-danger&title=" + URLEncoder.encode("修改密码") + "&context=" + URLEncoder.encode("修改失败，用户名：") + username + URLEncoder.encode("不存在") + "&preview=manager.jsp");
            }
        } else {
            toPath += ("state=panel-danger&title=" + URLEncoder.encode("修改密码") + "&context=" + URLEncoder.encode("修改失败，信息不完整") + "&preview=manager.jsp");
        }
        response.sendRedirect(toPath);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
